/*
* OSS自动上传代码
* 参数 UPLOAD_PATH 上传路径
* 参数 UPLOAD_REPLACE 文件路径需要进行字符串替换的部分
* 参数 UPLOAD_PROCESS 上传的进程数
* 参数 CDN_PREFIX 预热文件URL前缀
* */
var co = require('co')
var OSS = require('ali-oss')
var fs = require('fs')
var path = require('path')
var cdnPreHot = require('./cdn')

var client = new OSS({
  region: 'oss-cn-beijing',
  accessKeyId: 'LTAIy6iMpNHarJWk',
  accessKeySecret: 'AYxxOPmpvlDxDoUuuY1VcNv7jRnZZv'
})
client.useBucket('zsz-oss')

var relate = process.env.UPLOAD_PATH ? process.env.UPLOAD_PATH : './dist'
var replace_string = process.env.UPLOAD_REPLACE

var readPath = path.join(__dirname, relate)
var process_count = process.env.UPLOAD_PROCESS ? Number(process.env.UPLOAD_PROCESS) : 5
var cdn_prefix = process.env.CDN_PREFIX ? process.env.CDN_PREFIX : 'https://static.zszweb.cn/'
var cdn_prefix2 = process.env.CDN_PREFIX2 ? process.env.CDN_PREFIX2 : 'https://static.zszweb.cn/'
var count = 0
var start = new Date().getTime()
console.log(cdn_prefix);
console.log(cdn_prefix2);

function readDir(readPath) {
  fs.readdir(readPath, function (err, files) {
    var splitFiles = splitArray(files, process_count)
    for (var i = 0; i < splitFiles.length; i++) {
      upload(splitFiles[i], readPath)
    }
  })
}

function splitArray (array, part) {
  var result = []
  var number = Math.ceil(array.length / part)
  for (var i = 0; i < part; i++) {
    result.push(array.slice(i * number, (i + 1) * number))
  }
  return result
}

function upload (files, readPath) {
  co(function*() {
    for (var i = 0; i < files.length; i++) {
      var nowPath = `${readPath}/${files[i]}`
      if (fs.lstatSync(nowPath).isDirectory()) {
        readDir(nowPath)
      } else {
        var filename = path.join(readPath, files[i])
        //oss名称 后-源文件
        var oss_name = path.relative(__dirname, filename).replace('..\\', '').replace('../', '').replace(/\\/g, '/')
        if (replace_string) {
          oss_name = oss_name.replace(replace_string, '')
        }
        yield client.put(oss_name, filename)
        console.log('上传成功' + oss_name)
        cdnPreHot(cdn_prefix + oss_name)
        cdnPreHot(cdn_prefix2 + oss_name)
      }
    }
  }).then(function () {
    ++count
    if (count == process_count) {
      console.log(`上传结束------${(new Date().getTime() - start) / 1000}S`)
    }
  }).catch(function (err) {
    console.log(`上传失败${err}`)
    console.log(`再次上传`)
    upload(files, readPath)
  })
}

readDir(readPath)
